/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apt;

import java.io.*;
import java.util.Date;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

/**
 *
 * @author PhiNguyen
 */
public class SendMailTest {

    public static void send(String smtpServer, String to, String from,
            String psw, String subject, String body) throws Exception {
        Properties props = System.getProperties();
        props.put("mail.smtp.host", smtpServer);
        props.put("mail.smtp.port", 587);
        props.put("mail.smtp.starttls.enable", true);
        props.put("mail.smtp.password", "password");
        final String name = from;// "nth001@gmail.com";//usermail
        final String pwd = psw;// "password cua ban o day";
        Authenticator pa = null; // default: no authentication
        if (name != null && pwd != null) { // authentication required?
            props.put("mail.smtp.auth", true);
            pa = new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(name, pwd);
                }
            };
        }
        Session session = Session.getDefaultInstance(props, null);
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        msg.setSubject(subject);
        msg.setText(body);
        msg.setHeader("X-Mailer", "LOTONtechEmail");
        msg.setSentDate(new Date());
        Transport transport = session.getTransport("smtp");
        transport.connect(null, name, pwd); //host, 25, "myemailhere", "mypasshere");
        msg.saveChanges();
        transport.sendMessage(msg, msg.getAllRecipients());
        Transport.send(msg);
        System.out.println("Message sent OK.");
    }

    public static void main(String[] args) {
        try {
            String smtpServer = "smtp.gmail.com";

            String to = "thering_gvn@yahoo.com";

            String from = "fifi.hate.lonely@gmail.com";

            String subject = "Hello from Java";

            String body = "Test using java to send mail.";

            String password = "theringxxx";

            send(smtpServer, to, from, password, subject, body);

            System.out.println("Finish!");
        } catch (Exception ex) {
            System.out.println("Usage: " + ex.getMessage());
        }
    }
}
